package com.example.su_shi_tan_mine.child

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.example.library_common.utils.normalShortToast
import com.example.su_shi_tan_bas_lib.base.BaseFragmentEx
import com.example.su_shi_tan_bas_lib.base.BaseLazyDataBindingFragment
import com.example.su_shi_tan_bas_lib.constant.CLICK_BLE
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.OnTextListener
import com.example.su_shi_tan_bas_lib.utils.timer.BaseTimerTask
import com.example.su_shi_tan_bas_lib.utils.timer.ITimerListener
import com.example.su_shi_tan_mine.R
import com.example.su_shi_tan_mine.databinding.ReSettingSignInPasswordFragmentBinding
import java.util.*

class ReSettingSignInPasswordFragment :
    BaseLazyDataBindingFragment<ReSettingSignInPasswordFragmentBinding>(), ReSettingPassWordLab,
    View.OnClickListener, OnTextListener, ITimerListener {


    companion object {
        fun newInstance(): ReSettingSignInPasswordFragment {
            val args = Bundle()
            val fragment = ReSettingSignInPasswordFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override val labInfo = "登录密码"

    private var phone = ""

    private var newPassword = ""

    private var finalPassword = ""

    private var vailCode = ""

    private var verifyEtvStr = ""

    private var mTimerTask: BaseTimerTask? = null

    private var mTimer: Timer? = null

    private var timer = 60

    private val handler: Handler = Handler(Looper.getMainLooper())

    override fun layoutId(): Int {
        return R.layout.re_setting_sign_in_password_fragment
    }

    override fun lazyInit() {
        viewBinder.onViewClick = this
        viewBinder.onTextListener = this
    }

    override fun initView(view: View) {
        view.setBackgroundColor(Color.TRANSPARENT)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnChange -> {
                if (checkInfo()) {
                    sending()
                }
            }
            R.id.mRequired -> {
                if (!CLICK_BLE) return
                CLICK_BLE = false
                sendingVerifyCoding()
            }
        }
    }

    private fun sendingVerifyCoding() {
        if (phone.isEmpty()) {
            CLICK_BLE = true
            normalShortToast(_mActivity, "请输入手机号")
            return
        }
        RestClient.builder()
            .url(R.string.register_verify)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "phone" to phone
                    )
                )
            )
            .success {
                CLICK_BLE = true
                startTimer()
            }.failure {
                CLICK_BLE = true
                normalShortToast(_mActivity, R.string.net_work_failed)
            }
            .error { _, msg ->
                CLICK_BLE = true
                normalShortToast(_mActivity, msg)
            }.build().post()
    }

    private fun startTimer() {
        if (mTimerTask !== null) return


        mTimer = Timer()

        mTimerTask = BaseTimerTask(this)
        mTimer?.schedule(mTimerTask, 1000, 1000)
    }

    private fun stopTimer() {


        if (mTimer != null) {
            mTimer?.cancel()
            mTimer = null
        }

        if (mTimerTask != null) {
            mTimerTask?.cancel()
            mTimerTask = null
        }
        CLICK_BLE = true
        viewBinder.mRequired.setText(R.string.require_verify_coding)
    }

    private fun sending() {
        RestClient.builder()
            .url(R.string.register_reset)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "account" to phone,
                        "captcha" to verifyEtvStr,
                        "password" to finalPassword,
                        "type" to 0
                    )
                )
            ).success {
                normalShortToast(_mActivity,"修改成功")
                if (parentFragment is BaseFragmentEx){
                    (parentFragment as BaseFragmentEx).pop()
                }
            }.failure {
                normalShortToast(_mActivity,R.string.net_work_failed)
            }.error { _, msg ->

                normalShortToast(_mActivity,msg)
            }.build().post()
    }

    private fun checkInfo(): Boolean {
        var flag = true
        if (newPassword.isEmpty()) {

            normalShortToast(_mActivity, "新密码不能为空")

            flag = false
        } else if (newPassword != finalPassword) {

            normalShortToast(_mActivity, "新密码与确认密码不一致")

            flag = false
        } else if (!viewBinder.mVerifyCode.isEqualsIgnoreCase(vailCode)) {

            normalShortToast(_mActivity, "图形验证码错误")

            flag = false
        } else if (verifyEtvStr.isEmpty()) {
            normalShortToast(_mActivity, "输入短信验证码")
            flag = false
        }

        return flag
    }

    override fun onDestroy() {
        super.onDestroy()
        stopTimer()
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.phone -> {
                phone = s.toString()
            }
            R.id.newPassword -> {
                newPassword = s.toString()
            }
            R.id.finalPassword -> {
                finalPassword = s.toString()
            }
            R.id.vailCode -> {
                vailCode = s.toString()
            }

            R.id.verifyEtv -> {
                verifyEtvStr = s.toString()
            }

        }
    }

    @SuppressLint("SetTextI18n")
    override fun onTimer() {
        handler.post {

            timer--

            if (timer < 0) {
                stopTimer()
            } else {
                viewBinder.mRequired.text = "${timer}秒后自动取消"
            }

        }
    }


}